﻿using AutoMapper;
using MediatR;
using SlaughterItem.Common.Domains.UPCTable;
using SlaughterItem.Common.Dtos;
using SlaughterItem.Common.Infrastructures.Interfaces;
using SlaughterItem.Enum;

namespace SlaughterItem.API.Application.Commands.Week02.UPC
{
    //添加商品代号
    public class AddUPCDataHandler : IRequestHandler<AddUPCDataCommand, Result>
    {
        public AddUPCDataHandler(IBaseRepository<UPCData> uPCDataRepository, IMapper mapper)
        {
            UPCDataRepository = uPCDataRepository;
            this.mapper = mapper;
        }

        public  IBaseRepository<UPCData> UPCDataRepository { get; set; }
        public IMapper mapper { get; set; }
        public async Task<Result> Handle(AddUPCDataCommand request, CancellationToken cancellationToken)
        {
            var result=new Result() { Code=(int)CommonErrorCode.Added};
            var DataNum = UPCDataRepository.GetAll().FirstOrDefault(x => x.UPCDataName == request.UPCDataName);
            if (DataNum == null)
            {
                var list = mapper.Map<UPCData>(request);
                var AddNum = UPCDataRepository.Add(list);
                if (AddNum > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    return result;
                }
                else
                {
                    return result;
                }
            }
            else
            {
                return result;
            }
        }
    }
}
